package com.zis.platform.common.authentication;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zis.platform.common.util.CacheCoreUtil;
import com.zis.platform.core.entity.SysEntity;

/**
 * 
 * <b>说明：</b> 鉴权之后的处理（拦截器）<br>
 * 登录成功则跳转到首页
 * 
 * @ClassName: CoreFormAuthenticationFilter
 * @author zhaohaitao(2543)
 * @date 2015-7-10 上午10:05:20
 * 
 */
public class CoreFormAuthenticationFilter extends FormAuthenticationFilter
{
    private Logger logger = LoggerFactory.getLogger(CoreFormAuthenticationFilter.class);
    
    /**
     * 返回URL
     */
    public static final String REDIRECT_URL = "redirectUrl";
    
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception
    {
        HttpServletRequest req = (HttpServletRequest)request;
        SysEntity sysInfo = CacheCoreUtil.getSysInfo(req);
        setLoginUrl(sysInfo.getLoginUrl());
        setSuccessUrl(sysInfo.getWelcomeUrl());
        boolean isAllowed = isAccessAllowed(request, response, mappedValue);
        // 登录跳转
        if (isAllowed && isLoginRequest(request, response))
        {
            try
            {
                issueSuccessRedirect(request, response);
            }
            catch (Exception e)
            {
                logger.error("", e);
            }
            return false;
        }
        return isAllowed || onAccessDenied(request, response, mappedValue);
    }
    
    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response)
        throws Exception
    {
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request);
        if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase("GET"))
        {
            Subject subject = SecurityUtils.getSubject();
            UserToken user = (UserToken)subject.getPrincipal();
            String redirectUrl = savedRequest.getRequestUrl();
            user.setRedirectUrl(redirectUrl);
        }
        WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
        throws Exception
    {
        return super.onAccessDenied(request, response);
    }
    
}
